﻿using System.Collections.Generic;
using UnityEngine;
using WorldMapBase.Tile.Pool;

namespace WorldMapBase.Tile
{
    public class TreeObject : WorldObject
    {
        private readonly List<Renderer> shadows = new List<Renderer>(16);
        
        private ScaleTreePrefabPool.ScaleTreeParams treeParams;

        public override void OnCreate(int lodIndex, int resID, Transform tf)
        {
            base.OnCreate(lodIndex, resID, tf);

            //现在树的阴影变成一个材质球了,而不是节点,所以先删了,因为会gc
            /*shadows.Clear();
            var children = tf.GetComponentsInChildren<Renderer>();
            foreach (var child in children)
                if (child.name == "shadow")
                {
                    child.enabled = lodIndex <= 2;
                    shadows.Add(child);
                }
            */
            if (lodIndex <= 1)
            {
                c = this;
                ScaleTreePrefabPool.ScaleTreeParamDic.TryGetValue(tf, out treeParams);
            }
        }

        public override void SetOpenUp(int lodLevel, float percent)
        {
            // 开关树的阴影
            foreach (var renderer in shadows)
                renderer.enabled = lodLevel <= 2;

            if (lodLevel > 0) 
                return;

            if (treeParams?.ChildTrees == null) 
                return;

            int count = treeParams.ChildTrees.Length;
            if (count == 0) 
                return;

            float scale = percent / 100.0f;
            scale = (1.414f - 1) * (1 - scale) + scale;

            for (int i = 0; i < count; i++) 
                treeParams.ChildTrees[i].localScale = treeParams.TreeScale[i] * scale;
        }


        public override void OnRecovered()
        {
            if (treeParams != null && treeParams.ChildTrees != null)
                for (int i = 0; i < treeParams.ChildTrees.Length; i++)
                    treeParams.ChildTrees[i].localScale = treeParams.TreeScale[i];
            treeParams = null;

            shadows.Clear();

            ClassPoolManager.RecoverTreeObject(this);
        }
    }
}
